package com.xuantu.learn.core.thread;

public class SynchronizedTest {

	class Bussiness {
		private boolean subFlag = true;

		public synchronized void mainThread() throws InterruptedException {
			while (subFlag) {
				wait();
			}
			for (int i = 0; i < 5; i++) {
				System.out.println(Thread.currentThread().getName() + " : main thread running loop count -- " + i);
				Thread.sleep(1000L);
			}
			subFlag = true;
			notify();
		}

		public synchronized void subThread() throws InterruptedException {
			while (!subFlag) {
				wait();
			}
			for (int i = 0; i < 10; i++) {
				System.out.println(Thread.currentThread().getName() + " : sub thread running loop count -- " + i);
				Thread.sleep(1000L);
			}
			subFlag = false;
			notify();
		}
	}

	public static void main(String[] args) throws InterruptedException {
		final Bussiness bussiness = new SynchronizedTest().new Bussiness();
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					for (int i = 0; i < 3; i++) {
						bussiness.subThread();
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

		}).start();
		for (int i = 0; i < 3; i++) {
			bussiness.mainThread();
		}
	}

}
